package com.nali.dal.mongo.dao.general;

import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.nali.dal.dao.general.IGeneralInsertDao;
import com.nali.dal.ds.IDataSource;
import com.nali.dal.ds.UsingDataSource;

public class MongoGeneralInsertDao implements IGeneralInsertDao, UsingDataSource<DB> {
	private DB db;
	private WriteConcern concern=WriteConcern.SAFE;
	
	public MongoGeneralInsertDao() {
		super();
	}

	public MongoGeneralInsertDao(WriteConcern concern, IDataSource<DB> ds) {
		this(concern, ds.getConnection());
	}

	public MongoGeneralInsertDao(WriteConcern concern, DB db) {
		super();
		this.concern = concern;
		this.db = db;
	}

	@Override
	public void insert(String collectionName, Map<String, Object> data) {
		DBCollection collection = db.getCollection(collectionName);
		BasicDBObject obj = new BasicDBObject();
		obj.putAll(data);
		try {
			collection.insert(obj, concern);
		} catch (MongoException e) {
			throw ExceptionTraner.tranException(e);
		}
	}

	@Override
	public void setDataSource(IDataSource<DB> ds) {
		this.db = ds.getConnection();		
	}

}
